package org.bhf.providers.resolvers;

import org.bhf.i18n.ContextLocation;
import org.bhf.service.ViewResolver;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.util.Locale;
import java.util.Set;

/**
 * Default view resolver, which resolves views by current <code>Locale</code>.
 */
public class I18nViewResolver implements ViewResolver
{
    /**
     * Resolve a view by locale.
     * @param viewBase The view base of the <code>Module</code>.
     * @param viewName The view name, as returned by <code>Page.getViewResource()</code>.
     * @param request the <code>ServletRequest</code>.  Must not be <code>null</code>.
     * @return Resolved path to view.
     */
    public String  resolveView( final String viewBase, final String viewName, final HttpServletRequest request )
    {
        final ServletContext    context     = request.getSession( true ).getServletContext();
        final ContextLocation   location    = ContextLocation.getCurrentContextLocation();
        final Locale            locale;

        // Location is first. Locale is guaranteed non-null
        if( location != null )
        {
            locale = location.getLocale(); // will not be null
        }
        else
        {
            locale = request.getLocale();
        }

        // Strip extension
        final String    baseName;
        final String    extension;
        {
            final int i = viewName.lastIndexOf( '.' );

            if( i == -1 )
            {
                baseName    = viewName;
                extension   = "";
            }
            else
            {
                baseName    = viewName.substring( 0, i );
                extension   = viewName.substring( i );
            }
        }

        final Set views = context.getResourcePaths( viewBase );

        if( views == null )
            throw new RuntimeException( "SWF view base path " + viewBase + " does not exist." );

        // 1 - language_coutry
        {
            final String resolvedView = viewBase + baseName + "_" + locale.getLanguage() + "_" + locale.getCountry() + extension;

            if( views.contains( resolvedView ) )
                return resolvedView;
        }

        // 2 - language
        {
            final String resolvedView = viewBase + baseName + "_" + locale.getLanguage() + extension;

            if( views.contains( resolvedView ) )
                return resolvedView;
        }

        // Punt
        return viewBase + viewName;
    }

    public void validateConfiguration()
    {
    }

    public Object decorate()
    {
        return this;
    }
}

